<template>
  <div class="form-container">
    <el-row :gutter="15">
      <el-col
        :xs="24"
        :sm="24"
        :md="12"
        :lg="12"
        :xl="12"
      >
        <el-tabs
          type="border-card"
          :value="tabName"
        >
          <el-tab-pane name="assetsForm">
            <span slot="label"><i class="el-icon-date" /> 资产名称</span>
            <el-form
              ref="assets"
              :model="assetsForm"
              :rules="rules"
              label-width="100px"
              class="demo-ruleForm"
            >
              <el-form-item
                v-if="user.level < 3"
                label="所属村"
                prop="village"
              >
                <el-cascader
                  v-model="assetsForm.villageWrap"
                  :options="villageCascader"
                  :props="villageProp"
                  @change="change"
                />
              </el-form-item>

              <el-form-item
                label="所属组"
                prop="group"
              >
                <el-select
                  v-model.number="assetsForm.group"
                  placeholder="请选择所属组"
                  clearable
                >
                  <el-option
                    v-for="item in groupAtt"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item
                label="资产类型"
                prop="type"
              >
                <el-select
                  v-model="assetsForm.type"
                  placeholder="请选择资产类型"
                >
                  <el-option
                    v-for="item in typeAtt"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item
                label="名称"
                prop="name"
              >
                <el-input v-model="assetsForm.name" />
              </el-form-item>

              <el-form-item>
                <el-button @click="resetForm('assetsForm')">
                  重置
                </el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane name="nonOperatingAssetsForm">
            <span slot="label"><i class="el-icon-goods" /> 非经营性资产</span>
            <el-form
              ref="nonOperatingAssets"
              :model="nonOperatingAssetsForm"
              :rules="rules"
              label-width="100px"
              class="demo-ruleForm"
            >
              <el-col
                :xs="24"
                :sm="24"
                :md="12"
                :lg="8"
                :xl="12"
              >
                <el-form-item label="计量单位">
                  <el-input v-model="nonOperatingAssetsForm.unitOfMeasurement" />
                </el-form-item>
                <el-form-item label="单价">
                  <el-input v-model="nonOperatingAssetsForm.unitPrice" />
                </el-form-item>
                <el-form-item label="现今价值">
                  <el-input v-model="nonOperatingAssetsForm.presentValue" />
                </el-form-item>
                <el-form-item label="规格型号">
                  <el-input v-model="nonOperatingAssetsForm.sizeAndModel" />
                </el-form-item>
                <el-form-item label="产品来源">
                  <el-input v-model="nonOperatingAssetsForm.source" />
                </el-form-item>
                <el-form-item label="使用部门">
                  <el-input v-model="nonOperatingAssetsForm.useDepartmentsAndUser" />
                </el-form-item>
                <el-form-item label="产品状态">
                  <el-input v-model="nonOperatingAssetsForm.productStatus" />
                </el-form-item>
              </el-col>
              <el-col
                :xs="24"
                :sm="24"
                :md="12"
                :lg="8"
                :xl="12"
              >
                <el-form-item label="数量">
                  <el-input v-model="nonOperatingAssetsForm.quantity" />
                </el-form-item>
                <el-form-item label="变动情况">
                  <el-input v-model="nonOperatingAssetsForm.changes" />
                </el-form-item>
                <el-form-item label="品牌">
                  <el-input v-model="nonOperatingAssetsForm.brand" />
                </el-form-item>
                <el-form-item label="构建时间">
                  <el-date-picker
                    v-model="nonOperatingAssetsForm.creationTime"
                    align="right"
                    type="date"
                    placeholder="选择日期"
                    value-format="yyyy-MM-dd"
                    :picker-options="pickerOptions"
                  />
                </el-form-item>
                <el-form-item label="预计年限">
                  <el-input v-model="nonOperatingAssetsForm.estimatedYears" />
                </el-form-item>
              </el-col>

              <el-col
                :xs="24"
                :sm="24"
                :md="12"
                :lg="8"
                :xl="24"
              >
                <el-form-item label="备注">
                  <el-input
                    v-model="nonOperatingAssetsForm.remarks"
                    type="textarea"
                    :autosize="{ minRows: 12}"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button @click="resetForm('nonOperatingAssetsForm')">
                    重置
                  </el-button>
                </el-form-item>
              </el-col>
            </el-form>
          </el-tab-pane>
          <el-tab-pane name="operatingAssetsForm">
            <span slot="label"><i class="el-icon-edit-outline" /> 经营性资产</span>
            <el-form
              ref="operatingAssets"
              :model="operatingAssetsForm"
              :rules="rules"
              label-width="100px"
              class="demo-ruleForm"
            >
              <el-col
                :xs="24"
                :sm="24"
                :md="12"
                :lg="8"
                :xl="12"
              >
                <el-form-item label="承租方">
                  <el-input v-model="operatingAssetsForm.lessee" />
                </el-form-item>
                <el-form-item label="合同期限">
                  <el-input v-model="operatingAssetsForm.durationOfCooperation" />
                </el-form-item>
                <el-form-item label="合同状态">
                  <el-input v-model="operatingAssetsForm.contractStatus" />
                </el-form-item>
              </el-col>
              <el-col
                :xs="24"
                :sm="24"
                :md="12"
                :lg="8"
                :xl="12"
              >
                <el-form-item label="签订合同">
                  <el-select
                    v-model="operatingAssetsForm.contractSigned"
                    clearable
                    placeholder="请选择"
                  >
                    <el-option
                      label="是"
                      :value="true"
                    />
                    <el-option
                      label="否"
                      :value="true"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="支付情况">
                  <el-input v-model="operatingAssetsForm.paymentStatus" />
                </el-form-item>
                <el-form-item label="合同金额">
                  <el-input v-model="operatingAssetsForm.amount" />
                </el-form-item>
              </el-col>

              <el-col
                :xs="24"
                :sm="24"
                :md="12"
                :lg="8"
                :xl="24"
              >
                <el-form-item label="备注">
                  <el-input
                    v-model="operatingAssetsForm.remarks"
                    type="textarea"
                    :autosize="{ minRows: 5}"
                  />
                </el-form-item>

                <relatedDocuments
                  :related-documents="documents"
                  @getRes="getResRelatedDocuments"
                />

                <el-form-item>
                  <el-button @click="resetForm('nonOperatingAssetsForm')">
                    重置
                  </el-button>
                </el-form-item>

                <el-form-item>
                  <el-button
                    type="primary"
                    @click="submitForm('operatingAssetsForm')"
                  >
                    {{ !id ? "立即创建" : "保存编辑" }}
                  </el-button>
                  <el-button
                    type="danger"
                    @click="resetForm('operatingAssetsForm')"
                  >
                    全部重置
                  </el-button>
                </el-form-item>
              </el-col>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-col>
      <el-col
        :xs="24"
        :sm="24"
        :md="12"
        :lg="8"
        :xl="10"
      />
      <el-col
        :xs="24"
        :sm="24"
        :md="12"
        :lg="8"
        :xl="10"
      />
    </el-row>
  </div>
</template>

<script>
//手动添加
import { mapGetters } from "vuex";
import relatedDocuments from "@/components/My-Components/relatedDocuments";
export default {
  name: "Form",
  components: {
    relatedDocuments,
  },
  props: {
    id: {
      type: String,
      required: false
    },
  },
  data() {
    return {
      tabName: "assetsForm",
      assetsForm: {
        villageWrap: [],
        village: "",
        group: "",
        name: "",
        type: "",
        operatingAssets: "",
        nonOperatingAssets: "",
      },
      operatingAssetsForm: {
        lessee: "",
        // contractSigned: true,
        durationOfCooperation: "",
        paymentStatus: "",
        contractStatus: "",
        // amount: "",
        remarks: "",
        relatedDocuments: [],
      },
      nonOperatingAssetsForm: {
        unitOfMeasurement: "",
        // quantity: "",
        // unitPrice: "",
        changes: "",
        // presentValue: "",
        brand: "",
        sizeAndModel: "",
        // creationTime: "",
        source: "",
        estimatedYears: "",
        useDepartmentsAndUser: "",
        productStatus: "",
        remarks: ""
      },
      rules: {
        name: [
          { required: true, message: "请输入资产名称", trigger: "blur" },
        ],
        village: [
          { required: true, message: "请选择所属村", trigger: "change" },
        ],
        type: [
          { required: true, message: "请选择资产类型", trigger: "change" },
        ],
      },
      pickerOptions: {
          disabledDate(time) {
            return false
          },
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }]
        },
      options: [],
      dialogImageUrl: "",
      dialogVisible: false,
      // fileList: [],
      createForm: {},
      villageCascader: [],
      groupAtt: [],
      villageProp: {
        value: "id",
        label: "name",
      },
      typeAtt: [],
      relatedDocuments: [],
      documents: [],
    };
  },
  computed: {
    ...mapGetters({
      user: "user/info",
    }),
  },
  async created() {
    this.init();
    // console.log(JSON.stringify(this.villageCascader))
    this.id && this.fetchData(this.id);
  },
  methods: {
    submitForm(formName) {
      this.$refs['assets'].validate((valid) => {
        if (valid) {
          if(this.id) {
            this.edit()
          } else {
            this.create();
          }
        } else {
          this.tabName = "assetsForm"
          // return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    getResRelatedDocuments(val) {
      this.relatedDocuments = val
      console.log(this.relatedDocuments)
    },
    resPip() {
      this.createForm = JSON.parse(JSON.stringify(this.assetsForm));
      this.createForm.operatingAssets = JSON.parse(JSON.stringify(this.operatingAssetsForm));
      this.createForm.nonOperatingAssets = JSON.parse(JSON.stringify(this.nonOperatingAssetsForm));
      this.createForm.operatingAssets.relatedDocuments = this.relatedDocuments
      this.clearNullField(this.createForm, 'group')
    },
    async create() {
      this.resPip();
      const res = await this.$http.post(`/assets`, this.createForm);
      if (res.status == 201) {
        this.$baseMessage("新增成功", "success");
        this.$router.push({ name: "Assets" });
      } else {
        this.$baseMessage("新增失败", "error");
      }
    },
    async edit() {
      this.resPip();
      const res = await this.$http.put(`/assets/${this.id}`, this.createForm);
      if (res.status == 200) {
        this.$baseMessage("修改成功", "success");
        this.$router.push({ name: "Assets" });
      } else {
        this.$baseMessage("修改失败", "error");
      }
    },
    async fetchData(id) {
      const res = await this.$http.get(`assets/${id}?join=village&join=nonOperatingAssets&join=operatingAssets&join=type&join=group`);

      const town = await this.$http.get(`village/${res.data.village.id}?join=town`);

      const area = await this.$http.get(`town/${town.data.town.id}?join=area`);
      res.data.villageWrap = [
        area.data.area.id,
        town.data.town.id,
        res.data.village.id,
      ];
      this.change([
        area.data.area.id,
        town.data.town.id,
        res.data.village.id,
      ])

      // res.date.group = res.date.group.id

      this.assetsForm = Object.assign({}, res.data);
      console.log(this.assetsForm)
      this.nonOperatingAssetsForm = Object.assign({}, res.data.nonOperatingAssets);
      this.operatingAssetsForm = Object.assign({}, res.data.operatingAssets);
      this.relatedDocuments = this.operatingAssetsForm.relatedDocuments
      this.documents = this.operatingAssetsForm.relatedDocuments
      
      console.log(this.operatingAssetsForm);
    },
    async init() {
      const res = await this.$http.get(`area?join=town&join=town.village`);
      res.data.forEach(area => {
        area.children = area.town
        area.town.forEach(town => {
          town.children = town.village
        })
      })
      this.villageCascader = res.data;
      this.setSelectItem()
    },
    async change(val) {
      this.assetsForm.village = val[val.length - 1];
      this.assetsForm.type = "";
      const res = await this.$http.get(`village/${this.assetsForm.village}?join=assetsType&join=group`);
      this.typeAtt = res.data.assetsType;
      this.groupAtt = res.data.group
    },

    setSelectItem() {
      if(this.user.level < 1) {
      } else if (this.user.level == 1) {
        //区级
        this.villageCascader.forEach((area) => {
          if(area.id == this.user.area.id) {
            area.disabled = false
          } else {
            area.disabled = true
            if (area.town.length > 0) {
              area.town.forEach((town) => {
                town.disabled = true
              });
            }
          }
        });
      } else if (this.user.level == 2) {
        //镇级
        this.villageCascader.forEach((area) => {
          if(area.id == this.user.area.id) {
            area.disabled = false
             if (area.town.length > 0) {
              area.town.forEach((town) => {
                if(town.id == this.user.town.id) {
                  town.disabled = false
                } else {
                  town.disabled = true
                }
              });
            }
          } else {
            area.disabled = true
            if (area.town.length > 0) {
              area.town.forEach((town) => {
                  town.disabled = true
              });
            }
          }
        });
      } 
        else if (this.user.level == 3) {
          //村级
        this.assetsForm.village = this.user.village.id
        this.change([this.assetsForm.village])
      } 
    },
  },
};
</script>

<style>
.el-col {
  border-radius: 4px;
}
.bg-purple-dark {
  background: #99a9bf;
}
.bg-purple {
  background: #d3dce6;
}
.bg-purple-light {
  background: #e5e9f2;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
</style>